<template>
  <div class="app-container">
    <PlatformHeader />
    <div class="main-container" :style="{ height: `calc(100vh - 72px)` }">
      <!-- 左侧面板 - 地区选择树 -->
      <div
        class="left-panel"
        :class="{ 'hidden': leftPaneSize === 0 }"
        :style="{ width: `${leftPaneSize}%` }"
      >
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入机构名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </div>

      <!-- 右侧主内容区 -->
      <div class="right-panel">
        <!-- 显示/隐藏左侧面板的按钮 -->
        <button
          class="toggle-btn"
          @click="toggleLeftPane"
          :style="{ left: leftPaneSize === 0 ? '10px' : `${leftPaneSize}%` }"
        >
          <i class="el-icon-s-fold" v-if="leftPaneSize > 0"></i>
          <i class="el-icon-s-unfold" v-else></i>
        </button>

        <el-col style="height: 100%;display: flex;flex-direction: column;padding: 10px;padding-top: 20px">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px" class="search-form custom-form" :rules="formRules">
            <el-form-item label="机构" prop="deptId" required label-width="60px">
              <el-input
                v-model="selectedNodeInfo"
                placeholder="请从左侧选择机构"
                readonly
                clearable
                style="width: 220px;background-color: transparent;"
                @focus="handleInputFocus"
              />
            </el-form-item>

            <!-- 修改为日期范围选择器 -->
            <el-form-item label="日期范围" prop="dateRange" required label-width="80px">
              <el-date-picker
                popper-class="custom-select-dropdown"
                v-model="queryParams.dateRange"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 212px"
                :picker-options="pickerOptions"
                @change="handleDateChange"
              />
            </el-form-item>
            <!-- 性别筛选 -->
            <el-form-item label="性别" prop="gender" label-width="40px">
              <el-select popper-class="custom-select-dropdown" v-model="queryParams.gender" placeholder="请选择性别" clearable style="width: 80px">
                <el-option
                  v-for="item in genderOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <!-- 人群筛选 -->
            <el-form-item label="人群分类" prop="populationType" required label-width="80px">
              <el-select
                popper-class="custom-select-dropdown"
                v-model="queryParams.populationType"
                placeholder="请选择"
                clearable
                style="width: 100px"
                @change="handlePopulationChange"
              >
                <el-option
                  v-for="item in populationOptions"
                  :key="item.id"
                  :label="item.peopletypename"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <!-- 动态年龄组筛选 -->
            <el-form-item label="年龄组" prop="ageGroup" label-width="60px">
              <el-select
                popper-class="custom-select-dropdown"
                v-model="queryParams.ageGroup"
                placeholder="请选择"
                clearable
                style="width: 122px"
                :disabled="!queryParams.populationType"
                @change="handleAgeGroupChange"
              >
                <el-option
                  v-for="item in ageGroupOptions"
                  :key="item.id"
                  :label="item.peaplegroupname"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <!-- 动态城乡工作种类筛选 -->
            <el-form-item label="城乡工作种类" prop="urbanRuralType">
              <el-select
                popper-class="custom-select-dropdown"
                v-model="queryParams.urbanRuralType"
                placeholder="请选择城乡工作种类"
                clearable
                style="width: 160px"
                :disabled="!queryParams.populationType"
              >
                <el-option
                  v-for="item in filteredUrbanRuralOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" class="search-btn action-btn" :disabled="!isFormValid">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" class="reset-btn action-btn">重置</el-button>
              <el-button icon="el-icon-map-location" size="mini" @click="showGpsDialog" class="action-btn add-btn" v-hasPermi="['monitordata:gps:add']">GPS</el-button>
              <el-button icon="el-icon-video-camera" size="mini" @click="resetQuery" class="action-btn edit-btn">监控</el-button>
            </el-form-item>
          </el-form>

          <!-- 添加表格父级容器，设置flex:1 -->
          <div class="table-container">
            <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange" class="custom-table">
              <el-table-column label="人群" align="center" prop="peopletypename" sortable />
              <el-table-column label="城乡工作种类" align="center" prop="towncountry" sortable />
              <el-table-column label="年龄组" align="center" prop="agegroupname" sortable />
              <el-table-column label="性别" align="center" prop="sex" sortable />
              <el-table-column label="目标人数" align="center" prop="samplenum" sortable />
              <el-table-column label="完成人数" align="center" prop="wancheng" sortable />
              <el-table-column label="初筛通过" align="center" prop="ispass" sortable />
              <el-table-column label="指标异常" align="center" prop="isnotpass" sortable />
              <el-table-column label="初筛完成率(%)" align="center" prop="ispasspercentage" sortable />
              <el-table-column label="检测完成率(%)" align="center" prop="finishper" sortable />
            </el-table>
          </div>
        </el-col>
      </div>
    </div>

    <!-- 修改后的GPS对话框 -->
    <el-dialog v-dialog-drag custom-class="custom-dialog" title="新增GPS坐标" :visible.sync="gpsDialogVisible" width="24%">
      <!-- 显示当前GPS信息 -->
      <div v-if="currentGps" class="current-gps-info">
        当前GPS: {{ currentGps }}
      </div>

      <div class="gps-input-container">
        <!-- 经度输入行 -->
        <div class="gps-input-row">
          <span class="coordinate-label">经度:</span>
          <el-input
            v-model="longitudePart1"
            placeholder="整数部分"
            style="width: 150px"
            class="coordinate-input"
            @input="handleIntegerInput('longitudePart1', $event)"
            @change="validateCoordinatePart('longitude', longitudePart1, 0)"
            type="text"
          ></el-input>
          <span class="decimal-separator"> . </span>
          <el-input
            v-model="longitudePart2"
            placeholder="小数部分"
            style="width: 150px"
            class="coordinate-input"
            @input="handleDecimalInput('longitudePart2', $event)"
            @change="validateCoordinatePart('longitude', longitudePart2, 1)"
            type="text"
          ></el-input>
        </div>
        <div class="error-message" v-if="longitudeError">{{ longitudeError }}</div>

        <!-- 纬度输入行 -->
        <div class="gps-input-row">
          <span class="coordinate-label">纬度:</span>
          <el-input
            v-model="latitudePart1"
            placeholder="整数部分"
            style="width: 150px"
            class="coordinate-input"
            @input="handleIntegerInput('latitudePart1', $event)"
            @change="validateCoordinatePart('latitude', latitudePart1, 0)"
            type="text"
          ></el-input>
          <span class="decimal-separator"> . </span>
          <el-input
            v-model="latitudePart2"
            placeholder="小数部分"
            style="width: 150px"
            class="coordinate-input"
            @input="handleDecimalInput('latitudePart2', $event)"
            @change="validateCoordinatePart('latitude', latitudePart2, 1)"
            type="text"
          ></el-input>
        </div>
        <div class="error-message" v-if="latitudeError || otherError">
          {{ latitudeError || otherError }}
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmGps" :loading="gpsLoading">保存GPS</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { deptTreeSelect } from "@/api/system/user";
import PlatformHeader from '../../../components/PlatformHeader/index.vue';
import { getPeopletypelist, getPeoplegroup } from "../../../api/monitormanage/indicator";
import { qualityMonitorData, creategpslist, addCreategps } from '@/api/monitormanage/testpeoplelog';
import { getUserProfile } from "@/api/system/user";

export default {
  name: "Testpeople",
  components: { PlatformHeader },
  data() {
    const validateDateRange = (rule, value, callback) => {
      if (!value || value.length !== 2) {
        callback(new Error('请选择完整的日期范围'));
      } else {
        const startDate = new Date(value[0]);
        const endDate = new Date(value[1]);
        if (startDate.getFullYear() !== endDate.getFullYear()) {
          callback(new Error('开始日期和结束日期必须在同一年内'));
        } else {
          callback();
        }
      }
    };
  // 获取默认日期范围
    const getDefaultDateRange = () => {
      const today = new Date();
      const currentYear = today.getFullYear();
      const startDate = `${currentYear}-01-01`;
      const endDate = today.toISOString().split('T')[0];
      return [startDate, endDate];
    };

    const defaultRange = getDefaultDateRange();
    return {
      leftPaneSize: 0, // 左侧面板占16%宽度
      deptName: '', // 地区搜索关键词
      selectedNodeInfo: '', // 选中的地区信息
      deptOptions: undefined, // 地区树形数据
      defaultProps: {
        children: "children",
        label: "label"
      },
      startYear: null, // 初始化 startYear

      // GPS相关数据
      gpsDialogVisible: false,
      gpsLoading: false,
      longitudePart1: '',
      longitudePart2: '',
      latitudePart1: '',
      latitudePart2: '',
      longitudeError: '',
      latitudeError: '',
      otherError: '',
      currentGps: '', // 当前GPS信息
      gpsList: [], // 存储获取的GPS列表

      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 表格数据
      tableData: [],
      // 人群选项 - 从API获取
      populationOptions: [],
      // 年龄组选项 - 从API获取
      ageGroupOptions: [],
      // 性别选项
      genderOptions: [
        { value: '', label: '全部' },
        { value: '男', label: '男' },
        { value: '女', label: '女' }
      ],
      // 所有城乡工作种类选项
      allUrbanRuralOptions: {
        '全部': [{ value: '全部', label: '全部' }],
        '幼儿': [
          { value: '全部', label: '全部' },
          { value: '农村幼儿', label: '农村幼儿' },
          { value: '城镇幼儿', label: '城镇幼儿' }
        ],
        '成年': [
          { value: '全部', label: '全部' },
          { value: '城镇体力劳动者', label: '城镇体力劳动者' },
          { value: '城镇非体力劳动者', label: '城镇非体力劳动者' },
          { value: '农民', label: '农民' }
        ],
        '老年': [
          { value: '全部', label: '全部' },
          { value: '农村老年人', label: '农村老年人' },
          { value: '城镇老年人', label: '城镇老年人' }
        ]
      },
      // 查询参数
      queryParams: {
        deptId: null,
        dateRange: defaultRange,
        startDate: defaultRange[0],
        endDate: defaultRange[1],
        populationType: 'all',
        ageGroup: '全部',
        urbanRuralType: '全部',
        gender: '',
        ageMin: null,
        ageMax: null
      },
      gpsParams: {
        deptid: null,
        year: null,
        id:null,
      },
      // 表单验证规则
      formRules: {
        deptId: [
          { required: true, message: '请选择机构', trigger: ['change', 'blur'] }
        ],
        dateRange: [
          { validator: validateDateRange, trigger: ['change', 'blur'] }
        ],
        populationType: [
          { required: true, message: '请选择人群分类', trigger: ['change', 'blur'] }
        ]
      },
      // 日期选择器配置
      pickerOptions: {
        disabledDate: (time) => {
          // 如果没有选择开始日期或者已经清除了选择，只禁用未来日期
          if (!this.startYear) {
            return time.getTime() > Date.now();
          }

          // 如果已经选择了开始日期，限制只能选择同一年份
          const timeYear = time.getFullYear();
          return time.getTime() > Date.now() || timeYear !== this.startYear;
        },
        onPick: ({ maxDate, minDate }) => {
          if (minDate) {
            // 保存选中的开始日期年份
            this.startYear = minDate.getFullYear();
          } else {
            // 如果没有选择日期，清除年份限制
            this.startYear = null;
          }
        },
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        },{
          text: '本年至今', //
          onClick(picker) {
            const end = new Date();
            const start = new Date(end.getFullYear(), 0, 1);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    };
  },
  computed: {
    isFormValid() {
      return this.queryParams.deptId && this.queryParams.dateRange && this.queryParams.populationType;
    },
    // 根据选择的人群过滤城乡工作种类选项
    filteredUrbanRuralOptions() {
      if (!this.queryParams.populationType) {
        return [{ value: '全部', label: '全部' }];
      }

      const selectedPopulation = this.populationOptions.find(item => item.id === this.queryParams.populationType);
      const populationName = selectedPopulation ? selectedPopulation.peopletypename : '';

      if (populationName.includes('幼儿')) {
        return this.allUrbanRuralOptions['幼儿'];
      } else if (populationName.includes('成年')) {
        return this.allUrbanRuralOptions['成年'];
      } else if (populationName.includes('老年')) {
        return this.allUrbanRuralOptions['老年'];
      }

      return [{ value: '全部', label: '全部' }];
    }
  },
  watch: {
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    'queryParams.populationType'(newVal) {
      if (newVal) {
        const selectedPopulation = this.populationOptions.find(item => item.id === newVal);
        if (selectedPopulation) {
          this.queryParams.ageMin = selectedPopulation.peopleagemin;
          this.queryParams.ageMax = selectedPopulation.peopleagemax;
          this.getAgeGroups(newVal);
        }
      } else {
        this.queryParams.ageGroup = null;
        this.ageGroupOptions = [];
        this.queryParams.ageMin = null;
        this.queryParams.ageMax = null;
      }
    }
  },
  methods: {
    /** 查询机构下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
        this.queryParams.deptId = response.data[0].id
        this.selectedNodeInfo = response.data[0].label

        // 确保数据加载完成后执行搜索
        this.$nextTick(() => {
          this.handleQuery();
        });
      });
    },

    /** 获取人群分类列表 */
    getPopulationTypes() {
      getPeopletypelist().then(response => {
        // 添加"全部"选项
        this.populationOptions = [{ id: 'all', peopletypename: '全部' }, ...response];
      });
    },

    /** 获取年龄组列表 */
    getAgeGroups(peopleTypeId) {
      if (peopleTypeId === 'all') {
        // 如果选择了"全部"，则获取所有年龄组
        this.ageGroupOptions = [{ id: 'all', peaplegroupname: '全部' }];
        this.queryParams.ageGroup = 'all';
        return;
      }

      getPeoplegroup(peopleTypeId).then(response => {
        const allAgeGroup = {
          id: 'all',
          peaplegroupname: '全部',
          agemin: this.populationOptions.find(item => item.id === peopleTypeId)?.peopleagemin,
          agemax: this.populationOptions.find(item => item.id === peopleTypeId)?.peopleagemax
        };
        this.ageGroupOptions = [allAgeGroup, ...response];
        this.queryParams.ageGroup = 'all';
        this.handleAgeGroupChange('all');
      });
    },

    /** 切换左侧面板显示/隐藏 */
    toggleLeftPane() {
      if (this.leftPaneSize === 0) {
        this.leftPaneSize = 16;
      } else {
        this.leftPaneSize = 0;
      }
    },

    /** 处理输入框获取焦点事件 */
    handleInputFocus() {
      this.leftPaneSize = 16;
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.selectedNodeInfo = data.label;
      this.leftPaneSize = 0;
      this.$refs.queryForm.clearValidate(['deptId']);
    },

    // 日期范围变化事件
    handleDateChange(val) {
      if (val && val.length === 2) {
        this.queryParams.startDate = val[0];
        this.queryParams.endDate = val[1];

        const startDate = new Date(val[0]);
        const endDate = new Date(val[1]);

        if (startDate.getFullYear() !== endDate.getFullYear()) {
          this.$message.error('错误：开始日期和结束日期必须在同一年内！');
          this.queryParams.dateRange = [];
          this.queryParams.startDate = null;
          this.queryParams.endDate = null;
          this.startYear = null; // 清除年份限制
        } else {
          this.startYear = startDate.getFullYear(); // 设置当前选择的年份
          this.$refs.queryForm.clearValidate(['dateRange']);
        }
      } else {
        // 当清空选择时，重置所有相关变量
        this.queryParams.startDate = null;
        this.queryParams.endDate = null;
        this.queryParams.dateRange = null;
        this.startYear = null; // 重要：清除年份限制
      }
    },

    // 人群选择变化时重置年龄组和城乡工作种类
    handlePopulationChange() {
      this.queryParams.ageGroup = null;
      this.queryParams.urbanRuralType = '全部';

      // 如果选择了"全部"，则获取所有年龄组
      if (this.queryParams.populationType === 'all') {
        this.getAgeGroups('all');
      }
    },

    // 年龄组选择变化事件
    handleAgeGroupChange(value) {
      if (value) {
        const selectedAgeGroup = this.ageGroupOptions.find(item => item.id === value);
        if (selectedAgeGroup) {
          this.queryParams.ageMin = selectedAgeGroup.agemin;
          this.queryParams.ageMax = selectedAgeGroup.agemax;
        }
      } else {
        const selectedPopulation = this.populationOptions.find(item => item.id === this.queryParams.populationType);
        if (selectedPopulation) {
          this.queryParams.ageMin = selectedPopulation.peopleagemin;
          this.queryParams.ageMax = selectedPopulation.peopleagemax;
        }
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.$refs.queryForm.validate(valid => {
        if (valid) {
          this.loading = true;
          console.log(this.queryParams)
          const qualityMonitorDataParams = {
            deptid: this.queryParams.deptId,
            starttime: this.queryParams.startDate,
            endtime: this.queryParams.endDate,
            year: this.queryParams.startDate ? this.queryParams.startDate.substring(0, 4) : null,
            ageMin: this.queryParams.ageMin,
            ageMax: this.queryParams.ageMax,
            sex: this.queryParams.gender,
            towncountry:this.queryParams.urbanRuralType=== '全部' ? null : this.queryParams.urbanRuralType,
            // 添加人群类型参数
            peopletypeid: this.queryParams.populationType === 'all' ? null : this.queryParams.populationType
          };

          qualityMonitorData(qualityMonitorDataParams).then(response => {
            this.tableData = response;
            this.loading = false;
          }).catch(() => {
            this.loading = false;
          });
        }
      });
    },

    /** 显示GPS对话框 */
    showGpsDialog() {
      this.gpsDialogVisible = true;
      this.resetGpsInputs();
      this.getCurrentGps();
    },

    /** 获取当前GPS信息 */
    async getCurrentGps() {
      try {
        const response = await creategpslist(this.gpsParams);
        console.log(response)
        if (response && response.rows[0] && response.rows[0].gps) {
          this.currentGps = response.rows[0].gps;
          // id去除
          //this.gpsParams.id = response.rows[0].id;
        }
      } catch (error) {
        console.error('获取GPS列表失败:', error);
        this.$message.error('获取GPS列表失败');
      }
    },

    /** 重置GPS输入框 */
    resetGpsInputs() {
      this.longitudePart1 = '';
      this.longitudePart2 = '';
      this.latitudePart1 = '';
      this.latitudePart2 = '';
      this.longitudeError = '';
      this.latitudeError = '';
      this.otherError = '';
    },

    // 处理整数部分输入
    handleIntegerInput(field, value) {
      // 只允许数字输入
      let filteredValue = value.replace(/[^0-9]/g, '');

      // 限制最大长度为3位
      if (filteredValue.length > 3) {
        filteredValue = filteredValue.slice(0, 3);
      }

      this[field] = filteredValue;
    },

    // 处理小数部分输入
    handleDecimalInput(field, value) {
      // 只允许数字输入
      let filteredValue = value.replace(/[^0-9]/g, '');

      // 限制最大长度为6位
      if (filteredValue.length > 6) {
        filteredValue = filteredValue.slice(0, 6);
      }

      this[field] = filteredValue;
    },

    // 清除所有GPS错误
    clearGpsErrors() {
      this.longitudeError = '';
      this.latitudeError = '';
      this.otherError = '';
    },

    // 设置GPS错误信息
    setGpsError(type, message) {
      if (type === 'longitude') {
        this.longitudeError = message;
      } else if (type === 'latitude') {
        this.latitudeError = message;
      } else {
        this.otherError = message;
      }
    },

    // 验证坐标部分
    validateCoordinatePart(type, value, partType) {
      // 清除其他错误，但保留当前类型的错误
      if (type === 'longitude') {
        this.latitudeError = '';
        this.otherError = '';
      } else if (type === 'latitude') {
        this.longitudeError = '';
        this.otherError = '';
      }

      // 如果值为空，直接返回
      if (value === '' || value === null || value === undefined) {
        return true;
      }

      // 整数部分验证
      if (partType === 0) {
        const numValue = parseInt(value);
        const maxValue = type === 'longitude' ? 180 : 90;

        if (isNaN(numValue)) {
          this.setGpsError(type, '请输入有效数字');
          return false;
        }

        if (numValue > maxValue) {
          this.setGpsError(type, `${type === 'longitude' ? '经度' : '纬度'}整数部分超出范围(0~${maxValue})`);
          return false;
        }
      }

      // 小数部分验证
      if (partType === 1) {
        if (isNaN(value)) {
          this.setGpsError(type, '请输入有效数字');
          return false;
        }
      }

      return true;
    },

    // 检查坐标格式是否合法
    validateCoordinateFormat(coord) {
      // 检查是否为数字
      if (isNaN(coord)) {
        return false;
      }

      // 检查小数点后位数不超过6位
      const parts = coord.toString().split('.');
      if (parts.length > 1 && parts[1].length > 6) {
        return false;
      }

      return true;
    },

    // 组装完整的GPS坐标
    assembleGpsCoordinate() {
      // 检查各部分是否为空
      if (!this.longitudePart1 || !this.latitudePart1) {
        this.setGpsError('other', '请输入完整的GPS坐标');
        return null;
      }

      let longitude = this.longitudePart1;
      if (this.longitudePart2) {
        longitude += `.${this.longitudePart2}`;
      }

      let latitude = this.latitudePart1;
      if (this.latitudePart2) {
        latitude += `.${this.latitudePart2}`;
      }

      // 验证坐标格式
      if (!this.validateCoordinateFormat(longitude) || !this.validateCoordinateFormat(latitude)) {
        this.setGpsError('other', '坐标格式不正确，小数部分最多6位');
        return null;
      }

      return `${longitude},${latitude}`;
    },

    // 验证GPS格式（中国范围）
    validateGpsFormat(gps) {
      if (!gps) return false;

      const [longitudeStr, latitudeStr] = gps.split(',');
      const longitude = parseFloat(longitudeStr);
      const latitude = parseFloat(latitudeStr);

      // 精确的中国经度范围(73.55°E ~ 135.05°E)
      if (longitude < 73.55 || longitude > 135.05) {
        this.setGpsError('longitude', '经度超出中国范围(73.55~135.05)');
        return false;
      }

      // 精确的中国纬度范围(3.86°N ~ 53.55°N)
      if (latitude < 3.86 || latitude > 53.55) {
        // 特殊处理南海诸岛(北纬3.86°至21.33°)
        const isInSouthChinaSea = (
          (longitude >= 109.3 && longitude <= 117.8) &&
          (latitude >= 3.86 && latitude <= 21.33)
        );

        if (!isInSouthChinaSea) {
          this.setGpsError('latitude', '纬度超出中国范围(3.86~53.55)，且不在南海诸岛范围内');
          return false;
        }
      }

      return true;
    },

    // 检查GPS是否重复
    checkGpsDuplicate(newGps) {
      if (!this.currentGps) return false;

      const existingGpsList = this.currentGps.split(';');
      return existingGpsList.includes(newGps);
    },

    // 修改confirmGps方法
    async confirmGps() {
      this.clearGpsErrors();

      // 验证所有输入部分
      const validations = [
        this.validateCoordinatePart('longitude', this.longitudePart1, 0),
        this.validateCoordinatePart('latitude', this.latitudePart1, 0)
      ];
      if (this.longitudePart2) {
        validations.push(this.validateCoordinatePart('longitude', this.longitudePart2, 1));
      }
      if (this.latitudePart2) {
        validations.push(this.validateCoordinatePart('latitude', this.latitudePart2, 1));
      }

      // 如果验证失败，直接返回（错误信息已经通过validateCoordinatePart设置）
      if (validations.includes(false)) {
        return;
      }

      // 组装完整坐标
      const newGps = this.assembleGpsCoordinate();
      if (!newGps) {
        return; // assembleGpsCoordinate方法中已经设置了错误信息
      }

      // 验证中国范围
      if (!this.validateGpsFormat(newGps)) {
        return; // validateGpsFormat方法中已经设置了错误信息
      }

      // 检查是否重复
      if (this.checkGpsDuplicate(newGps)) {
        this.setGpsError('other', '该GPS坐标已存在');
        return;
      }

      try {
        this.gpsLoading = true;
        const response = await addCreategps({
          ...this.gpsParams,
          //gps: this.currentGps ? `${this.currentGps};${newGps}` : newGps
          gps: newGps // 直接使用新输入的GPS，不再拼接原有GPS
        });

        if (response.code === 200) {
          this.$message.success('GPS保存成功,请等待审核');
          this.gpsDialogVisible = false;
          this.currentGps = this.currentGps ? `${this.currentGps};${newGps}` : newGps;
          this.resetGpsInputs();
        } else {
          this.setGpsError('other', response.msg || 'GPS保存失败');
        }
      } catch (error) {
        console.error('保存GPS失败:', error);
        this.setGpsError('other', 'GPS保存失败');
      } finally {
        this.gpsLoading = false;
      }
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        deptId: null,
        dateRange: null,
        startDate: null,
        endDate: null,
        populationType: null,
        ageGroup: null,
        urbanRuralType: '全部',
        gender: '',
        ageMin: null,
        ageMax: null
      };
      this.selectedNodeInfo = '';
      this.startYear = null; // 清除年份限制
      this.ageGroupOptions = [];
      this.tableData = [];
      this.$refs.tree.setCurrentKey(null);
      this.$nextTick(() => {
        this.$refs.queryForm.clearValidate();
      });
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    }
  },
  created() {
    this.getDeptTree();
    this.getPopulationTypes();
    getUserProfile().then(response => {
      this.gpsParams.deptid = response.data.deptId;
      this.gpsParams.year = new Date().getFullYear();
    });

  }
};
</script>

<style scoped lang="scss">
.app-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: hidden;
  background: url('../../assets/images/bgn.png');
  background-size: 100% 100%;
  padding: 16px;
  box-sizing: border-box;
  padding-top: 0;
}

.main-container {
  position: relative;
  width: 100%;
  overflow: hidden;
}

/* 左侧面板样式 */
.left-panel {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background-color: #0160FA;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
  z-index: 10;
  transition: width 0.3s ease;
  overflow: auto;
  padding: 16px;
  box-sizing: border-box;
}

.left-panel.hidden {
  width: 0 !important;
  padding: 0;
}

/* 右侧面板样式 */
.right-panel {
  width: 100%;
  height: 100%;
  padding-left: 0;
  transition: padding-left 0.3s ease;
  box-sizing: border-box;
  overflow: auto;
}

/* 切换按钮样式 */
.toggle-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 10px;
  height: 30px;
  background-color: rgba(0,128,255,0.3);
  border: 1px solid #0080ff;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  z-index: 20;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: left 0.3s ease;
}

.toggle-btn i {
  color: #fff;
  font-size: 10px;
}

/* 表单样式调整 */
.search-form {
  .el-form-item {
    margin-right: 20px;
    margin-bottom: 18px;
  }

  .el-form-item__label {
    white-space: nowrap;
    padding-right: 8px;
    color: #fff!important;
  }
  ::v-deep .el-form-item__label {
    color: #fff;
  }
  .el-input, .el-select, .el-date-editor {
    width: 220px;
  }

  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 260px;
  }
}

/* 表格容器 - 添加flex:1 */
.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 树机构样式修改  */
::v-deep .el-tree {
  background: #0080FF;
  color: #fff;
  border-radius: 8px;
}
::v-deep .el-tree-node__content:hover {
  background-color: #0879e9;
}
::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-table__row {
  background-color: #0879e9;
}

/* 表格整体容器 */
::v-deep .el-table {
  background: transparent;
  border-radius: 12px;
  overflow: hidden;
  flex: 1;
  display: flex;
  flex-direction: column;

  /* 表头和表格体容器 */
  .el-table__header-wrapper,
  .el-table__body-wrapper {
    flex-shrink: 0;
  }

  /* 表格体容器 - 添加flex:1使其占据剩余空间 */
  .el-table__body-wrapper {
    flex: 1;
    overflow: auto;
  }

  /* 表头圆角 */
  .el-table__header-wrapper {
    border-radius: 12px;
  }

  /* 表格行圆角 */
  .el-table__body-wrapper {
    border-radius: 0 0 12px 12px;

    tr {
      td:first-child {
        border-bottom-left-radius: 12px;
      }
      td:last-child {
        border-bottom-right-radius: 12px;
      }
    }

    /* 为每一行添加圆角 */
    tr.el-table__row {
      td:first-child {
        border-top-left-radius: 12px;
        border-bottom-left-radius: 12px;
      }
      td:last-child {
        border-top-right-radius: 12px;
        border-bottom-right-radius: 12px;
      }
    }
  }
}
/* 确保表头单元格没有边框干扰圆角 */
::v-deep .el-table th.el-table__cell {
  border: none;
}
.el-table::before{
  height: 0;
}
::v-deep .el-table th.el-table__cell.is-leaf{
  border-bottom: none;
}
/* 表头 - 深蓝到青绿，柔和渐变 */
::v-deep .el-table th {
  background: #f7e797;
  color: #1e4f91; // 更深的蓝
  font-weight: bold;
  font-size: 18px;
  height: 30px;
  line-height: 30px;
}
/* 奇偶行 - 亮蓝与浅青 */
::v-deep .el-table__row {
  td {
    border: none; /* 移除单元格边框 */
  }
}

/* 奇偶行 - 亮蓝与浅青 */
::v-deep .el-table__row:nth-child(odd) {
  background: linear-gradient(90deg, #99e8ff, #4f85ff);
}
::v-deep .el-table__row:nth-child(even) {
  background: linear-gradient(90deg, #4f85ff, #99e8ff);
}

/* 单元格文字 */
::v-deep .el-table td {
  color: #000; /* 深灰色，更易读 */
  font-size: 18px;
  padding: 12px 8px;
}
::v-deep .el-table__body {
  border-collapse: separate !important;
  border-spacing: 0 5px !important;
}
/* 鼠标悬停 - 橙黄渐变 */
::v-deep .el-table__body tr:hover > td {
  background: #9ef7c5!important;
}

/* 美化 el-input 输入框 */
::v-deep .el-input .el-input__inner {
  background-color: rgba(255, 255, 255, 0.1); /* 半透明白背景 */
  border: 1px solid #00CCFE; /* 柔和的蓝色边框 */
  border-radius: 6px;
  color: #f0f0f0;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
  font-size: 16px;
}

/* 输入框 placeholder 颜色改为 #fff */
::v-deep .el-input__inner::placeholder {
  color: #fff !important;
}

/* 输入框获得焦点时边框高亮 */
::v-deep .el-input .el-input__inner:focus {
  border-color: #409eff; /* element-ui 默认蓝色 */
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.6);
  background-color: rgba(255, 255, 255, 0.15);
  color: #fff;
}

/* 清除按钮的颜色调整 */
::v-deep .el-input__clear {
  color: #a8c0ff;
}

/* 清除按钮 hover 颜色 */
::v-deep .el-input__clear:hover {
  color: #409eff;
}

/* 搜索区按钮美化 - 调大尺寸 */
::v-deep .el-form-item .el-button {
  border-radius: 22px;
  font-weight: 600;
  font-size: 16px;       /* 字号变大 */
  padding: 10px 21px;    /* 内边距加大 */
  transition: all 0.3s ease;
  box-shadow: 0 3px 8px rgba(66, 133, 244, 0.3);
}

/* 通用按钮基础样式 */
.el-button {
  font-size: 14px;
  padding: 10px 20px; /* 比默认稍大 */
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.25s ease;
}

/* 调整表单里的按钮间距 */
::v-deep .el-form-item .el-button {
  margin-left: 12px; /* 你可以改成 16px 更宽松 */
}
/* 按钮通用样式（不改尺寸） */
::v-deep .el-form-item .action-btn {
  border-radius: 20px; /* 圆润 */
  font-weight: 600;
  border: none;
  transition: all 0.3s ease;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);

}

/* 悬浮时按钮微微上浮 + 光晕 */
::v-deep .el-form-item .action-btn:hover {
  transform: translateY(-2px);
}

/* 搜索按钮 - 宝石蓝渐变 */
::v-deep .el-form-item .search-btn {
  background: linear-gradient(135deg, #b4cdeb, #2f6bcc);
  color: #fff;
}
::v-deep .el-form-item .search-btn:hover {
  background: linear-gradient(135deg, #5aa2f8, #3a8ef6);
  box-shadow: 0 6px 14px rgba(58, 142, 246, 0.5);
}

/* 重置按钮 - 高级灰蓝 */
::v-deep .el-form-item .reset-btn {
  background: linear-gradient(135deg, #df9f3f, #edc73d);
  color: #fff;
}
::v-deep .el-form-item .reset-btn:hover {
  background: linear-gradient(135deg, #ffcc80, #ffb74d);
  box-shadow: 0 6px 14px rgba(255, 183, 77, 0.5);
}
/* 新增按钮 - 蓝绿色渐变 */
::v-deep .el-form-item .add-btn {
  background: linear-gradient(135deg, #4fd1c5, #38b2ac);
  color: #fff;
}
::v-deep .el-form-item .add-btn:hover {
  background: linear-gradient(135deg, #6ee7df, #4fd1c5);
  box-shadow: 0 6px 14px rgba(72, 187, 176, 0.5);
}

/* 修改按钮 - 青柠绿渐变 */
::v-deep .el-form-item .edit-btn {
  background: linear-gradient(135deg, #8bc34a, #6fa33f);
  color: #fff;
}
::v-deep .el-form-item .edit-btn:hover {
  background: linear-gradient(135deg, #a8d672, #8bc34a);
  box-shadow: 0 6px 14px rgba(139, 195, 74, 0.5);
}
/* 美化日期选择框 */
::v-deep .el-date-editor {
  background-color: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid #00CCFE !important;
  border-radius: 6px;
  color: #f0f0f0 !important;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

::v-deep .el-date-editor:hover {
  border-color: #409eff !important;
}

::v-deep .el-date-editor .el-range-input {
  background-color: transparent !important;
  color: #fff !important;
}

::v-deep .el-date-editor .el-range-separator {
  color: rgba(255, 255, 255, 0.8) !important;
}

/* 日期选择框 placeholder 颜色改为白色 */
::v-deep .el-date-editor .el-range-input::placeholder {
  color: #fff !important;
}

/* 单个日期选择框（非范围） placeholder 颜色 */
::v-deep .el-date-editor input::placeholder {
  color: #fff !important;
}

/*css主要部分的样式*/
/*定义滚动条宽高及背景，宽高分别对应横竖滚动条的尺寸*/
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

/*定义滚动条的轨道颜色、内阴影及圆角*/
::-webkit-scrollbar-track{
  border-radius: 4px;
  background-color: rgb(1 96 250);
}

/*定义滑块颜色、内阴影及圆角*/
::-webkit-scrollbar-thumb{
  border-radius: 8px;
  background-color: #0080ff;
}

/*定义滑块悬停变化颜色、内阴影及圆角*/
::-webkit-scrollbar-thumb:hover{
  background-color: #C7C9CC;
}
::v-deep {

  .is-horizontal {
    height: 0px;
    left: 0px;
    display: none;
  }

}
/* 关键样式：调整输入框高度为36px */
::v-deep .custom-form .el-input__inner {
  height: 36px!important;
  line-height: 36px!important;
}

/* GPS对话框样式 */
.current-gps-info {
  margin-bottom: 15px;
  padding: 10px;
  background-color: transparent;
  font-size: 16px;
  border-radius: 8px;
  border: 1px solid #00ccfe;
  font-weight: bold;
  display: none;
}

.gps-input-container {
  margin: 15px 0;
}

.gps-input-row {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.coordinate-label {
  width: 50px;
  font-weight: bold;
  margin-right: 10px;
}

.decimal-separator {
  margin: 0 5px;
  font-weight: bold;
  margin-right: 10px;
  font-size: 20px;
}

.coordinate-input {
  margin-right: 5px;
}

/* 错误信息样式 */
.error-message {
  color: #ff4d4f;
  font-size: 18px;
  margin-top: 10px;
  margin-bottom: 10px;
  padding-left: 60px;
  min-height: 20px; /* 保持错误信息区域高度一致 */
}

/* 限制数字输入框的箭头 */
::v-deep .el-input-number .el-input__inner {
  text-align: left;
  padding-right: 15px;
}

/* 隐藏数字输入框的箭头 */
::v-deep input[type='number']::-webkit-outer-spin-button,
::v-deep input[type='number']::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
::v-deep input[type='number'] {
  -moz-appearance: textfield;
}

/* 对话框整体样式 - 添加渐变背景 */
::v-deep .custom-dialog {
  border-radius: 16px !important;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  background: linear-gradient(145deg, #f5f7fa, #e4e8f0);

  .el-dialog__header {
    background: linear-gradient(90deg, #8caefb, #0160FA);
    padding: 20px;
    margin: 0;
    border-bottom: none;

    .el-dialog__title {
      color: #fff;
      font-size: 20px;
      font-weight: 600;
      letter-spacing: 1px;
    }

    .el-dialog__headerbtn {
      top: 20px;
      right: 20px;

      .el-dialog__close {
        color: #fff;
        font-size: 20px;
      }
    }
  }

  /* 修改body部分为渐变 */
  .el-dialog__body {
    padding: 20px 40px 10px 40px;
    background: linear-gradient(145deg, #e6f0ff, #bad2ff);
    color: #333; /* 文字颜色调整 */
    .el-input__inner{
      color: #333;
    }
    ::v-deep .custominput {
      color: #ff0000;
    }
  }

  /* 修改footer部分为渐变 - 与body同色系但略深 */
  .el-dialog__footer {
    padding: 20px 40px;
    background: linear-gradient(145deg, #e6f0ff, #a2c3ff);
    border-top: 1px solid rgba(79, 133, 255, 0.1); /* 半透明分割线 */
    border-radius: 0 0 16px 16px;
  }
}

/* 表单元素样式调整以适应新背景 */
::v-deep .custom-input {
  .el-input__inner {
    background-color: transparent;
    border: 1px solid rgba(79, 133, 255, 0.3);
    color: #000;

    &:focus {
      border-color: #4f85ff;
      background-color: transparent;
      box-shadow: 0 0 0 2px rgba(79, 133, 255, 0.2);
    }
  }
}
::v-deep .custom-input.el-input .el-input__inner{
  border: 1px solid rgba(79, 133, 255, 0.3);

}
::v-deep .custominput .el-input__inner::placeholder{
  color: #333!important; //placeholder 文字颜色修改

}
::v-deep .el-tree-node:focus > .el-tree-node__content {
  background-color: transparent;
}
.dialog-footer {
  display: flex;
  justify-content: center; /* 改为居中 */
  align-items: center;
  gap: 20px; /* 添加按钮间距 */

  .el-button {
    min-width: 120px; /* 稍微加大按钮宽度 */
    height: 40px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    letter-spacing: 1px;
    transition: all 0.3s;
    margin: 0; /* 移除原来的margin-left */
  }

  .dialog-cancel-btn {
    border: none;
    background: linear-gradient(135deg, #aed7ff, #80bcf9);
    color: #fff;
    font-size: 16px;
    box-shadow: 0 6px 14px rgb(128 188 249 / 50%);
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }

  .dialog-confirm-btn {
    background: linear-gradient(90deg, #4f85ff, #6a8cff);
    border: none;
    color: #fff;
    font-size: 16px;
    box-shadow: 0 6px 14px rgb(128 188 249 / 50%);
    &:hover {
      background: linear-gradient(90deg, #3a73ff, #4f85ff);
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(79, 133, 255, 0.3);
    }

    &:active {
      transform: translateY(0);
    }
  }
}
::v-deep .custom-dialog .el-input__inner::placeholder{
  color: #333!important; //placeholder 文字颜色修改

}
</style>
